package com.book.controller;

import com.book.entity.BookCart;
import com.book.service.BookCartService;
import com.book.util.JsonResult;
import com.book.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author SuperYu  2024/7/30
 */

@Controller
@RequestMapping("/cart")
@Slf4j
public class BookCartController {
    @Resource
    BookCartService bookCartService;


    @GetMapping("/getCartNum")
    @ResponseBody
    public JsonResult<Integer> getCartNum(HttpSession session) {
        // 从数据库查出，当前用户的购物车数据
        Long userId = (Long) session.getAttribute("loginUserId");
        int result = bookCartService.findCartNumByUserId(userId.intValue());

        return JsonResult.ok(200, result);
    }

    @GetMapping("/searchByUserId")
    public String getCartByUserId(HttpSession session, Model model) {
        // 从数据库查出，当前用户的购物车数据
        Long userId = (Long) session.getAttribute("loginUserId");
        List<CartVo> list = bookCartService.findCartByUserId(userId.intValue());
        model.addAttribute("cartList",list);

        return "cart";
    }

    @PostMapping("/add")
    @ResponseBody
    public JsonResult<String> getCartNum(BookCart cart, HttpSession session) {
        // 从数据库查出，当前用户的购物车数据
        Long userId = (Long) session.getAttribute("loginUserId");

        cart.setUserId(userId.intValue());

        log.info("要添加进购物车的数据：" + cart);

        int result = bookCartService.addToCart(cart);
        if (result > 0) {
            return JsonResult.ok(200, "添加成功");

        } else {
            return JsonResult.error(500, "添加失败");

        }
    }

}
